/**
 * Created by Administrator on 2015/11/19.
 */
var conn = require('../util/conn');
var Q = require('q');
/**
 * department.parentId
 * callback(data)
 * data is database query result
 * @parentId
 * @callback
 */
var getDepartments = function(parentId,callback){
    var connection = conn.getConnection();
    connection.connect();
    var sql = '';
    if(!parentId){//parentId === undefined
        sql = 'select * from department where parentId is null';
    }
    else{
        sql = 'select * from department where parentId = ' + parentId;
    }
    var query = connection.query(sql,function(err,rows,fields){
        if(err) throw err;
        var retObj = [];
        for(var i in rows){
            var obj = { id:rows[i].id,
                        text:rows[i].name};
            getDepartments(rows[i].departmentId,function(data){
                if(data.length !== 0){
                    obj.children = data;
                }
                retObj.push(obj);
            });
            callback(retObj);
        }
        //callback(rows);
    })
};
/**
 *
 * @param id
 * @Return is a promise
 */
function getDepartmentByIdQ(id){
    var connection = conn.getConnection();
    connection.connect();
    var deferred = Q.defer();
    if(typeof id === 'string'){
        id = parseInt(id);
    }else if(typeof id !== 'number'){
        deferred.reject(new Error('id must be a number'));
    }
    var query = connection.query('select * from department where id = ?',[id],function(err,rows,fields){
        if(err){
            deferred.reject(err);
        }else{
             if(rows.length > 0){
                 deferred.resolve(rows[0]);
             }else{
                 deferred.resolve(undefined);
             }
            console.log(rows);
        }
        //callback(rows[0]);
    });
    console.log(query.sql);
    connection.end();
    return deferred.promise;
}
//var getDep = getDepartmentByIdQ(4);
//getDep.then(
//    function(d){
//        if(d !== undefined){
//            var obj = { id: d.id,
//                        text:d.name};
//            return getDepartmentByIdQ(d.parentId).then(
//                function(p){
//                    if(p!==undefined){
//                        obj.parent = {
//                            id:p.id,
//                            text: p.name
//                        }
//                    }
//                    console.log(obj);
//                }
//            )
//        }
//
//    }
//);
/**
 * v2
 * @param id
 * @returns {*}
 */

function getDepartmentByIdQ1(id){
    var connection = conn.getConnection();
    connection.connect();
    var deferred = Q.defer();
    if(typeof id === 'string'){
        id = parseInt(id);
    }else if(typeof id !== 'number'){
        deferred.reject(new Error('id must be a number'));
    }else{
        var query = connection.query('select * from department where id = ?',[id],function(err,rows,fields){
            if(err){
                deferred.reject(err);
            }else{
                if(rows.length > 0){
                    getDepartmentByIdQ1(rows[0].parentId).then(
                        function(data){
                            deferred.resolve({
                                id:rows[0].id,
                                text:rows[0].name,
                                parent:data
                            })
                        }
                    );
                    //deferred.resolve(rows[0]);
                }else{
                    deferred.resolve({});
                }
                console.log(rows);
            }
            //callback(rows[0]);
        });
        console.log(query.sql);
    }
    connection.end();
    return deferred.promise;
}
//getDepartmentByIdQ1(1).then(console.log);
/**
 * v3
 * @param id
 * @returns {*}
 */
function getDepartmentByIdQ2(id){
    var connection = conn.getConnection();
    connection.connect();
    var deferred = Q.defer();
    if(typeof id === 'string'){
        id = parseInt(id);
    }else if(typeof id !== 'number'){
        deferred.reject(new Error('id must be a number'));
    }else{
        var query = connection.query('select * from department where id = ?',[id],function(err,rows,fields){
            if(err){
                deferred.reject(err);
            }else{
                if(rows.length > 0){
                    //getDepartmentByIdQ1(rows[0].parentId).then(
                        //function(data){
                        //    deferred.resolve({
                        //        id:rows[0].id,
                        //        text:rows[0].name,
                        //        parent:data
                        //    })
                        //}
                    //);
                    deferred.resolve(rows[0]);
                }else{
                    deferred.resolve(undefined);
                }
                console.log(rows);
            }
            //callback(rows[0]);
        });
        console.log(query.sql);
    }
    connection.end();
    return deferred.promise;
}
//v3-1
/*
getDepartmentByIdQ2(4).then(function(data){
    if(data && data.parentId){
        console.log(data);
        getDepartmentByIdQ2(data.parentId).then(
            function(row){
                console.log('test');
                if(row){
                    console.log({
                        id:data.id,
                        text:data.name,
                        parent:{
                            id:row.id,
                            text:row.name
                        }
                    })
                }else{
                    console.log({
                        id:data.id,
                        text:data.name
                    })
                }
            }
        )
    }
    else{
        console.log({
            id:data.id,
            text:data.name
        });
    }
});
*/

/**
 * v3-2
 * 此版本工作非常好
 */
//getDepartmentByIdQ2(1).then(function(data){
//    if(data && data.parentId){
//        return [data,getDepartmentByIdQ2(data.parentId)];
//    }
//    return [data];
//}).spread(function(data,row){
//    console.log('++++++++++++++');
//    console.log(data);
//    console.log(row);
//});

/**
 * getDepartmentsQ v1
 * @param parentId
 * @param callback
 */

function getDepartmentsQ1(parentId){
    var connection = conn.getConnection();
    connection.connect();
    var deferred = Q.defer();
    if(typeof parentId === 'string'){
        parentId = parseInt(parentId);
    }else if(typeof parentId !== 'number'){
        deferred.reject(new Error('parentId must be a number'));
    }else{
        var query = connection.query('select * from department where parentId = ?',[parentId],function(err,rows,fields){
            if(err){
                deferred.reject(err);
            }else{
                if(rows.length > 0){
                    deferred.resolve(rows);
                }else{
                    deferred.resolve(undefined);
                }
                console.log(rows);
            }
            //callback(rows[0]);
        });
        console.log(query.sql);
    }
    connection.end();
    return deferred.promise;
}
getDepartmentsQ1(2).then(function(data){
    console.log(data);
});

/**
 * id = department.id
 * callback({
 *  id:
 *  name:
 *  parentId:
 * })
 * @param id
 * @param callback
 */

var getDepartment = function(id,callback){
    var connection = conn.getConnection();
    connection.connect();
    if(typeof id === 'string'){
        id = parseInt(id);
    }else if(typeof id !== 'number'){
        throw Error('id must be a number');
    }
    var query = connection.query('select * from department where id = ?',[id],function(err,rows,fields){
        if(err) throw err;
//        console.log(typeof rows);
//        console.log('++++++++++++++');
//        console.log(rows[0]);
        callback(rows[0]);
    });
    console.log(query.sql);
    connection.end();
};
//var q_getDepartment = Q.denodeify(getDepartment);
//var q_getDepartments = Q.denodeify(getDepartments);
//var promise = q_getDepartment(1);
//promise.then(function(data){
//    if(typeof data === 'object' && data.id !== undefined){
//        var retObj = {
//            id:data.id,
//            text:data.name
//        };
//        return q_getDepartments(data.id)
//            .then(function(rows){
//                var childeren = [];
//                for(var i in rows){
//                    var temp = {
//                        id:row[0].id,
//                        text:row[0].name
//                    }
//                    childeren.push(temp);
//                }
//                retObj.children = childeren;
//            });
//    }
//}).then();
//var promise1 = q_getDepartments(2);
//promise1.then(console.log,console.error);
var getUsers = function(page,rows,callback){

    var retObj = {};
    var connection = conn.getConnection();
    connection.connect();
    if(!page || !rows){
        page = 1;
        rows = 10;
    }
    else{
        page = parseInt(page);
        rows = parseInt(rows);
    }
    var start = (page-1)*rows;
    connection.query('select count(*) as result from user',function(err,rows,fields){
        retObj.result = rows[0].result;//获取总行数
    });
    var query = connection.query('select * from user limit ?,?',[start,rows], function(err, rows, fields) {
        if (err) throw err;

        datas = [];
        for(var row in rows){
            var node = {
                id:rows[row].id,
                name:rows[row].name
            }
            datas[row] = node;
        }
        retObj.rows = datas;
        callback(retObj);
    });
    console.log(query.sql);
    connection.end();
}
